import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../config/config.dart';
import '../services/screen_adapter.dart';
import '../provider/checkout.dart';
import '../provider/cart.dart';
import '../services/user_service.dart';
import '../services/sign_service.dart';
import '../services/event_bus.dart';
import '../services/checkout_service.dart';


class CheckOutPage extends StatefulWidget {
  CheckOutPage({Key key}) : super(key: key);

  @override
  _CheckOutPageState createState() => _CheckOutPageState();
}

class _CheckOutPageState extends State<CheckOutPage> {

  List _addressList = [];

  @override
  void initState() { 
    super.initState();
    _getDefaultAddress();

    /// 监听增加收货地址的广播
    eventBus.on<CheckOutEvent>().listen((event) {
      _getDefaultAddress();
    });
  }

  _getDefaultAddress() async {
    List userinfo = await UserService.getUserInfo();
    var tempJson = {
      'uid': userinfo[0]['_id'],
      'salt': userinfo[0]['salt']
    };

    var sign = SignService.getSign(tempJson);

    var api = '${Config.domain}api/oneAddressList?uid=${userinfo[0]['_id']}&sign=$sign';
    var response = await Dio().get(api);
    setState(() {
      _addressList = response.data['result'];
    });
    
  }

  Widget _checkoutItem(item) {
    return Row(
      children: <Widget>[
        Container(
          width: ScreenAdapter.width(160),
          child: Image.network('${item['pic']}', fit:BoxFit.cover)
        ),
        Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.fromLTRB(10, 10, 5, 10),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween, // 一个居上一个居下
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('${item['title']}', maxLines: 2),
                Text('${item['selectedAttr']}', maxLines: 2),
                Stack(
                  children: <Widget>[
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text('¥${item['price']}', style: TextStyle(
                        color: Colors.red
                      ))
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: Text('x${item['count']}')
                    )
                  ]
                )
              ]
            )
          )
        )
      ]
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init();
    List checkoutList = context.watch<CheckOut>().checkOutList;

    return Scaffold(
      appBar: AppBar(
        title: Text('结算'),
      ),
      body: Stack(
        children: <Widget>[
          ListView(
            children: <Widget>[
              Container(
                color: Colors.white,
                child: Column(
                  children: <Widget>[
                    SizedBox(height: 10),
                    _addressList.isEmpty ? ListTile(
                      leading: Icon(Icons.add_location),
                      title: Center(
                        child:  Text('请添加收货地址')
                      ),
                      trailing: Icon(Icons.navigate_next),
                      onTap: () {
                        Navigator.pushNamed(context, '/addressAdd');
                      }
                    ) : ListTile(
                      title: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text('${_addressList[0]['name']} ${_addressList[0]['phone']}'),
                          SizedBox(height: 10),
                          Text('${_addressList[0]['address']}')
                        ]
                      ),
                      trailing: Icon(Icons.navigate_next),
                      onTap: () {
                        Navigator.pushNamed(context, '/addressList');
                      }
                    ),
                    SizedBox(height: 10)
                  ]
                ) 
              ),
              SizedBox(height: 20),
              Container(
                padding: EdgeInsets.all(ScreenAdapter.width(20)),
                color: Colors.white,
                child: Column(
                  children: checkoutList.map((item) {
                    return Column(
                      children: <Widget>[
                        _checkoutItem(item),
                        Divider(),
                      ]
                    );
                  }).toList()
                  
                )
              ),
              SizedBox(height: 20),
              Container(
                color: Colors.white,
                padding: EdgeInsets.all(ScreenAdapter.width(20)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text('商品总金额：¥100'),
                    Divider(),
                    Text('立减：¥2'),
                    Divider(),
                    Text('运费：¥0')
                  ]
                )
              )

            ]
          ),
          Positioned(
            bottom: 0,
            width: ScreenAdapter.width(750),
            height: ScreenAdapter.height(100),
            child: Container(
              padding: EdgeInsets.all(5),
              width: ScreenAdapter.width(750),
              height: ScreenAdapter.height(100),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  top: BorderSide(
                    width: 1,
                    color: Colors.black26
                  )
                )
              ),
              child: Stack(
                children: <Widget>[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: <Widget>[
                        Text('总价:'),
                        Text('¥${CheckOutService.getAllPrice(checkoutList).toStringAsFixed(1)}', style: TextStyle(
                          color: Colors.red
                        ))
                      ],
                    )
                  ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: RaisedButton(
                      onPressed: () async{
                        if (_addressList.isNotEmpty) {
                          /// 获取商品数据
                          List userinfo = await UserService.getUserInfo();
                          ///注意：商品总价保留一位小数
                          var allPrice = CheckOutService.getAllPrice(checkoutList).toStringAsFixed(1);

                          //获取签名
                          var sign = SignService.getSign({
                            "uid": userinfo[0]["_id"],
                            "phone": this._addressList[0]["phone"],
                            "address": this._addressList[0]["address"],
                            "name": this._addressList[0]["name"],
                            "all_price": allPrice,
                            "products": json.encode(checkoutList),
                            "salt": userinfo[0]["salt"] //私钥
                          });
                          //请求接口
                          var api = '${Config.domain}api/doOrder';
                          var response = await Dio().post(api, data: {
                            "uid": userinfo[0]["_id"],
                            "phone": this._addressList[0]["phone"],
                            "address": this._addressList[0]["address"],
                            "name": this._addressList[0]["name"],
                            "all_price": allPrice,
                            "products": json.encode(checkoutList),
                            "sign": sign
                          });
                          // print(response);
                          if (response.data["success"]) {
                            /// 删除购物车已经提交的商品数据
                            await CheckOutService.removeSelectedCartItem();
                            /// 调用CartProvider更新购物车数据
                            context.read<Cart>().updateList();
                            /// 跳转支付页面
                            Navigator.pushNamed(context, '/pay', arguments: {
                              'allPrice': allPrice 
                            });
                          }

                        } else {
                          Fluttertoast.showToast(
                            msg: "请填写收货地址",
                            toastLength: Toast.LENGTH_SHORT,
                            gravity: ToastGravity.CENTER,
                            timeInSecForIosWeb: 1,
                            backgroundColor: Colors.grey[600],
                            textColor: Colors.white,
                            fontSize: 16.0
                          );
                        }
                        

                      },
                      child: Text('立即下单', style: TextStyle(
                        color: Colors.white
                      )),
                      color: Colors.red,
                    )
                  )
                ]
              )
            )
          )
        ]
      )
    );
  }
}